package org.example.dao;

import org.example.biz.HelloBiz;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy {

    public static <T> T proxy(T readSubject){
        return (T) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(),
                readSubject.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        method.setAccessible(true);
                        System.out.println("检查数据是否合法:" + args[0]);
                        Object ret = method.invoke(readSubject, args);
                        System.out.println("验证数据是否保存成功:" + args[0]);
                        return ret;
                    }
                });
    }

    public static void main(String[] args) {

        Object object = "abc";
        String a = object.toString();  // 正确  父类转子类, 只能转为原有类型
        Object o = object;             // 正确
        o = a;                         // 正确  父类指向子类对象
        Integer b = (Integer) object;  // 错误, 兄弟对象转型错误

        HardDisk hardDisk = new HardDisk();
        UsbDisk usbDisk = new UsbDisk();
        Storage proxyHardDisk = proxy(hardDisk);
        Storage proxyUsbDisk = proxy(usbDisk);
        // 通过代理执行业务方法
        System.out.println("---------------------------");
        proxyHardDisk.save("书籍");
        System.out.println("---------------------------");
        proxyUsbDisk.save("书籍");
        System.out.println("---------------------------");
        // 被代理对象必须实现接口
        HelloBiz helloBiz = proxy(new HelloBiz("张三"));
        helloBiz.hello();

    }


}
